package com.service.admin.qiniu.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.service.admin.qiniu.service.FileService;
import com.service.admin.qiniu.support.QnCloud;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

@Slf4j
@Service
public class FileServiceImpl implements FileService {

    @Autowired
    private QnCloud qnCloud;

    @Override
    public String uploadImag(MultipartFile file, String fileName) {
        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Region.huanan());
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);

        Auth auth = Auth.create(qnCloud.getAccessKey(), qnCloud.getSecretKey());
        String upToken = auth.uploadToken(qnCloud.getBucket());

        String result = null;

        try {
            Response response = uploadManager.put(file.getInputStream(), file.getSize(), fileName, upToken, null, null, false);
            //解析上传成功的结果
            DefaultPutRet putRet = JSONObject.parseObject(response.bodyString(), DefaultPutRet.class);

            log.info("{七牛图片上传key: " + putRet.key + ",七牛图片上传hash: " + putRet.hash + "}");

            result = qnCloud.getBucketDomain() + putRet.key;
        } catch (QiniuException ex) {
            Response r = ex.response;
            log.error(r.toString());
            result = null;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public String buildPublicUrl(@NotNull String fileName) throws UnsupportedEncodingException {
        String encodeFileName = URLEncoder.encode(fileName, "utf-8").replace("+", "%20");
        String publicUrl = String.format("%s/%s", qnCloud.getBucketDomain(), encodeFileName);
        Auth auth = Auth.create(qnCloud.getAccessKey(), qnCloud.getSecretKey());
        return auth.privateDownloadUrl(publicUrl, qnCloud.getExpireInSeconds());
    }
}
